<template>
  <div class="app-container">
    <div class="filter-container">
      <div style="text-align:center;font-size:20px;">
        <span>{{ className }}-本期学员{{ student_number }}名</span>
      </div>
      <el-button
        v-waves
        :loading="downloadLoading"
        style="float:right;"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出</el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
    >
      <el-table-column type="index" width="60" align="center" sortable="custom" />
      <el-table-column label="姓名" min-width="120" align="center" sortable="custom" prop="name">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="{row}">
          <span>{{ sexType[row.sex]['display_name'] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="籍贯" align="center" prop="provice">
        <template slot-scope="{row}">
          <span>{{ row.provice + row.city + row.county }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学校" align="center" prop="school">
        <template slot-scope="{row}">
          <span>{{ row.school }}</span>
        </template>
      </el-table-column>
      <el-table-column label="专业" align="center" prop="major">
        <template slot-scope="{row}">
          <span>{{ row.major }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学历" align="center" prop="education">
        <template slot-scope="{row}">
          <span>{{ row.education }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就业单位" align="center" prop="employment_unit">
        <template slot-scope="{row}">
          <el-input
            v-model="row.employment_unit"
            class="edit-input"
            size="small"
            @blur="edit(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="roles.includes('admin')"
        label="薪资"
        align="center"
        prop="salary"
        sortable="custom"
      >
        <template slot-scope="{row}">
          <el-input
            v-model="row.salary"
            class="edit-input"
            size="small"
            @blur="edit(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注（酷站）" align="center" prop="remarks">
        <template slot-scope="{row}">
          <el-input
            v-model="row.remarks"
            class="edit-input"
            size="small"
            @blur="edit(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.page_size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  fetchList,
  fetchEdit,
  fetchDelete,
  fetchDownload
} from '@/api/students'
import waves from '@/directive/waves' // waves directive
import { parseTime, download } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { sexType } from '@/utils/dataType'

export default {
  name: 'GraduateClassList',
  components: { Pagination },
  directives: { waves },
  filters: {
    dateFormat(time) {
      return parseTime(time, '{y}-{m}-{d}')
    }
  },
  data() {
    return {
      number: undefined,
      className: undefined,
      tableKey: 0,
      list: [],
      roles: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 10,
        class_id: undefined,
        begin_date: undefined,
        end_date: undefined,
        search: undefined,
        status: undefined,
        order: '-id'
      },
      downloadLoading: false,
      sexType
    }
  },
  watch: {
    '$route.query.id'() {
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.roles = this.$store.getters.roles || []
      const { student_number, className, id } = this.$route.query
      this.student_number = student_number
      this.className = className
      this.listQuery.class_id = id
      this.getList()
    },
    async getList() {
      try {
        this.listLoading = true
        const { data } = await fetchList(this.listQuery)
        const { data: list, total } = data
        list.map(v => {
          v._employment_unit = false
          v._salary = false
          v._remarks = false
        })
        this.list = list
        this.total = total
        this.listLoading = false
      } catch (e) {
        this.listLoading = false
      }
    },
    async edit(row) {
      try {
        this.dialogLoading = true
        const data = {
          id: row.id,
          employment_unit: row.employment_unit,
          salary: row.salary,
          remarks: row.remarks
        }
        await fetchEdit(data)
        this.dialogLoading = false
        this.$message({ message: '修改成功', type: 'success' })
        this.dialogFormVisible = false
      } catch (e) {
        this.dialogLoading = false
      }
    },
    handleDelete(row) {
      this.$confirm(`此操作不可恢复，确认要删除【${row.name}】学生吗？`)
        .then(_ => {
          try {
            ;(async () => {
              await fetchDelete(row.id)
              this.$message({ message: '删除成功', type: 'success' })
              await this.getList()
            })()
          } catch (e) {
            this.$message({ message: '删除失败', type: 'error' })
          }
        })
        .catch(_ => {})
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        this.sort(prop, order)
      } else {
        this.listQuery.sort = '-id'
        this.handleFilter()
      }
    },
    sort(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sort = `+${prop}`
      } else {
        this.listQuery.sort = `-${prop}`
      }
      this.handleFilter()
    },
    async handleDownload() {
      try {
        this.downloadLoading = true
        const { data } = await fetchDownload(this.listQuery)
        this.downloadLoading = false
        download(data, '学生毕业信息-' + new Date().getTime() + '.xlsx') // url时名字不起作用
      } catch (e) {
        this.downloadLoading = false
      }
      // import('@/vendor/Export2Excel').then(excel => {
      //   const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
      //   const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
      //   const data = this.formatJson(filterVal, this.list)
      //   excel.export_json_to_excel({
      //     header: tHeader,
      //     data,
      //     filename: 'table-list'
      //   })
      //   this.downloadLoading = false
      // })
    }
  }
}
</script>
